import { promises, readdirSync } from 'fs'
import MagicString from 'magic-string'
import { normalizePath } from 'vite'
export class Declaration{
  public path!:string
  public files!:string[]
  public comps!:string[]

  constructor(public readonly dir:string){}

  public create(){
   this.path = normalizePath(process.cwd()) + this.dir
   this.files = readdirSync(this.path)
  }

  public component(files:string[]){
    this.comps = files
      .filter((f)=>f.endsWith('.vue') && !f.startsWith("index") )
      .map((s)=> new MagicString(s).replaceAll(".vue","").toString().toLowerCase())
  }

  public transform(comps:string[]):string{
    const code = comps.map((v)=> `function ${v}(fn):[{value:boolean} , typeof import('vue')['ref']] ;`)
    const s = new MagicString(code.join('\n'));
    s.prepend("type fn = (params?:any)=> void \ndeclare namespace $dialog { \n").append("\n}")
    return s.toString()
  }

  public visable(path:string):boolean{
    if(!path.endsWith(".vue")) return false
    const files = readdirSync(this.path)
    if(files.length === this.files.length) return false 
    this.files = files
    return true
  } 

  public updatedts(){
    this.component(this.files)
    const s = this.transform(this.comps)
    this.wirtedts(s)
  }

  public wirtedts(s:string):void{
    promises.writeFile(this.path +  "/com.d.ts", s, 'utf-8')
  }
}